package guestbook.controlador;

import guestbook.persistencia.Usuario;
import guestbook.service.UsuarioService;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;


@Controller
@SessionAttributes({"usuario"})
public class UserController {

    
    private UsuarioService usuarioService;
    private AuthenticationManager authenticationManager ;

    
    
    @Autowired
    @Required
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Autowired
    @Required
    public void setUsuarioService(UsuarioService usuarioService) {
        this.usuarioService = usuarioService;
    }



    @RequestMapping(method=RequestMethod.GET, value="/getUsuarioConectado", headers="Accept=application/json")
    public @ResponseBody Usuario getUser() {
        return usuarioService.getCurrentUser();
    }



    
    @RequestMapping(method=RequestMethod.GET, value="/getLoginURL")
    public String getLoginURL() {
        return "/login";
    }


    @RequestMapping(method=RequestMethod.GET, value="/login", headers="Accept=application/json")
    public @ResponseBody String login(@RequestParam String username, @RequestParam String password, Model model) {
        String rdo = null;
        try {
                //System.out.println("AQUI 1 UserController login ");
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                //System.out.println("AQUI 2 UserController login ");
		UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
                //System.out.println("AQUI 3 UserController login ");
		authToken.setDetails(authentication.getDetails());
                //System.out.println("AQUI 4 UserController login authenticationManager="+authenticationManager);
		Authentication newAuth = authenticationManager.authenticate(authToken);
                //System.out.println("AQUI 5 UserController login ");
		SecurityContextHolder.getContext().setAuthentication(newAuth);
                //System.out.println("AQUI 6 UserController login ");
                if (newAuth.isAuthenticated()) {
                    model.addAttribute("usuario", usuarioService.getCurrentUser());
                    //rdo = "Estás conectado como" + username;
                } else {
                    rdo = "Error al conectar. Comprueba usuario y contraseña";

                }
                //System.out.println("AQUI 7 UserController login ");

	} catch (Exception unfe) {
		rdo =" ERROR " + unfe.getMessage();
                unfe.printStackTrace();
	}
        return rdo;
    }


    @RequestMapping(method=RequestMethod.GET, value="/logout")
    public String logout(HttpSession sesion, SessionStatus sessionStatus, @ModelAttribute("usuario") Usuario usuario) throws java.io.IOException {
        System.out.println("UsuarioController logout se está desconectando "+usuario.getUsername());
        SecurityContextHolder.getContext().setAuthentication(null);
        Usuario u = (Usuario) sesion.getAttribute("usuario");
        System.out.println("UsuarioController logout se está desconectando2 "+usuario.getUsername());        
        sessionStatus.setComplete();
        //Otra forma: sesion.invalidate();

        return "redirect:index.html";
    }

    
}
